package com.wocao.system.service.impl;

import com.wocao.commom.utils.CommonUtil;
import com.wocao.system.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * 邮件服务接口实现类
 *
 * @author sunhao
 * @date 2021/10/28
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String sendEmail;

    @Resource
    private JavaMailSender mailSender;

    @Override
    public String sendRegisterEmail(String toEmail) {
        try {
            String code = CommonUtil.randomNumber();
            String content = "你好！您的注册验证码: " + code + "， 请在五分钟内进行注册，过期无效。";
            SimpleMailMessage messege = new SimpleMailMessage();
            messege.setFrom(sendEmail);
            messege.setTo(toEmail);
            messege.setText(content);
            messege.setSubject("窝草平台邮件验证码");
            mailSender.send(messege);
            return code;
        } catch (MailException e) {
            log.error("EmailServiceImpl.sendEmail is error, toEmail={}", toEmail, e);
        }
        return null;
    }

}
